﻿using System.Collections;
using UniFramework.Machine;
using UnityEngine;
using YooAsset;

/// <summary>
/// 更新资源版本号
/// </summary>
internal class FsmUpdatePackageVersion : IStateNode
{
    private StateMachine _machine;

    void IStateNode.OnCreate(StateMachine machine)
    {
        _machine = machine;
    }
    void IStateNode.OnEnter()
    {
        PatchEventDefine.PatchStatesChange.SendEventMessage("获取最新的资源版本 !");
        BootManager.Instance.StartCoroutine(UpdatePackageVersion());
    }
    void IStateNode.OnUpdate()
    {
    }
    void IStateNode.OnExit()
    {
    }

    private IEnumerator UpdatePackageVersion()
    {
        yield return new WaitForSecondsRealtime(0.5f);

        var settings = (BootSettings)_machine.GetBlackboardValue("Settiings");
        var packageName = settings.DefaultPackage;

        var package = YooAssets.GetPackage(packageName);
        var operation = package.RequestPackageVersionAsync();
        yield return operation;

        if (operation.Status != EOperationStatus.Succeed)
        {
            //如果网络不通，读取本地版本号
            if (PlayerPrefs.HasKey(PlayerPrefsKey.LocalVersion))
            {
                Debug.Log("本地版本号" + PlayerPrefsKey.LocalVersion);
                ChangeStateToManifest(PlayerPrefs.GetString(PlayerPrefsKey.LocalVersion));
            }
            else
            {
                Debug.LogWarning(operation.Error);
                PatchEventDefine.PackageVersionUpdateFailed.SendEventMessage();
            }
        }
        else
        {
            //如果网络通
            Debug.Log($"Request package version : {operation.PackageVersion}");

            // 手动更新（远端获取） || 首次进入（streamAsset中获取） 
            if (PlayerPrefs.GetInt(PlayerPrefsKey.ManualUpdate, 0) == 1 || PlayerPrefs.GetString(PlayerPrefsKey.FirstVersion) == string.Empty)
            {
                ChangeStateToManifest(operation.PackageVersion);
            }
            else
            {
                //没有点不更新
                Debug.Log("不更新" + PlayerPrefsKey.LocalVersion);
                ChangeStateToManifest(PlayerPrefs.GetString(PlayerPrefsKey.LocalVersion));
            }

        }
        void ChangeStateToManifest(string version)
        {
            Debug.Log("ChangeStateToManifest" + version);
            _machine.SetBlackboardValue("PackageVersion", version);
            _machine.ChangeState<FsmUpdatePackageManifest>();
        }
    }
}